package com.ddyx.common.framework.aop.aspect;

import com.ddyx.common.framework.datasource.DataSource;
import com.ddyx.common.framework.datasource.DynamicDataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * <p>
 *      通过aop拦截，获取注解上面的value的值key，实现数据源的切换。
 * </p>
 * author: agula
 * since: 2019-07-16  19:31
 */
@Slf4j
@Aspect
@Component
public class DynamicDataSourceAspect {

    @Pointcut("@within(com.ddyx.common.framework.datasource.DataSource ) " +
            "|| @annotation(com.ddyx.common.framework.datasource.DataSource)")
    public void pointCut(){

    }

    @Before("pointCut() && @annotation(dataSource)")
    public void doBefore(DataSource dataSource){
        log.info("选择数据源---" + dataSource.value());
        DynamicDataSourceContextHolder.setDataSourceType(dataSource.value());
    }

    @After("pointCut()")
    public void doAfter(){
        DynamicDataSourceContextHolder.clearDataSourceType();
    }
}
